class Manage::FunctionsController < ApplicationController
  include Security::Session::Access
  include Utils::Url

  def list
    @functions = Function.find(:all, :order => "name")
  end

  def show
    @function = Function.find(id_param)
  end

  def update
    case request.method
    when :post
      @function = Function.find(params[:function][:id])
      params[:function].delete(:id)
      @function.attributes=(params[:function])
      if save_function?
        flash[:notice] = "Function successfully updated"
        redirect_to(:action => "show", :id => @function.id)
        return
      end 
    else
      @function = Function.find(id_param)
    end
  end

  private
    def save_function?
      if @function.save
        associate_folders
        return true
      end
      return false
    end

    def associate_folders
      a_folders = @function.folder.dup
      a_folders.each do |fldr|
        unless params.has_key?("folder_#{fldr.id}")
          FolderContent.delete_all("folder_id = #{fldr.id} and function_id = #{@function.id}") 
        end
      end

      params.each do |key,value|
        if key =~ /^folder_/
          id = get_id_from_param(key)
          if !@function.belongs_to_folder?(id)
            seq = FolderContent.get_next_seq(id)
            FolderContent.create(:folder_id => id, :function_id => @function.id, :seq => seq)
          end
        end
      end
    end
end
